var server = require('ws').Server;
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var http = require('http');
var interfaces = require('os').networkInterfaces(); // 在开发环境中获取局域网中的本机iP地址
var open = require("open");

var ws = new server({
	port:8003
});

// 从命令行参数获取root目录，默认是当前目录:
var root = path.resolve(process.argv[2] || '.');

let IPAdress = '';
for(var devName in interfaces){  
  var iface = interfaces[devName];  
  for(var i=0;i<iface.length;i++){  
        var alias = iface[i];  
        if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){  
              IPAdress = alias.address;  
        }  
  }  
} 
/**************************/
var MANAGER = "manager";
var SERVER = "server";
var CLIENT = "client";

var SCOKETS = {};
SCOKETS[MANAGER] = [];
SCOKETS[SERVER] = [];
SCOKETS[CLIENT] = [];

/***************************/
//函数参数，连接的对象
ws.on("connection",function(socket){
	socket.on("message",function(bundleStr){
        var bundle = JSON.parse(bundleStr);
        state(this, bundle);
	})
	//断开连接
	socket.on("close",function(){
        state(this, {"action":"close"});
	})
})

var groups = ""; 
/**
bundle = {
    "action" : "",
    "type" : "",
    "content" : "";
}
action = connect|close|chat;
type = MANAGER|SERVER|CLIENT;
content = 自定义
**/
function state(socket, bundle){
    switch(bundle.action)
    {
        case "connect":
            socket.c_type = bundle.type;
            SCOKETS[bundle.type].push(socket);
            if(socket.c_type == SERVER){
                socket.send(groups);
            }
        break;
        case "close":
            var ssArr = SCOKETS[socket.c_type];
            ssArr.splice(ssArr.indexOf(this),1);
        break;
        case "chat":
            if(socket.c_type == MANAGER){
                groups = JSON.stringify(bundle.content);
                var cArr = SCOKETS[CLIENT];
                for (var i = 0; i < cArr.length; i++) {
                    cArr[i].send(groups);
                }
                var sArr = SCOKETS[SERVER];
                for (var i = 0; i < sArr.length; i++) {
                    sArr[i].send(groups);
                }
            }
            if(socket.c_type == SERVER){
                var cArr = SCOKETS[CLIENT];
                for (var i = 0; i < cArr.length; i++) {
                    cArr[i].send(JSON.stringify(bundle.content));
                }
            }
        break;
    }
}


// 创建服务器:
var server = http.createServer(function (request, response) {
    // 获得URL的path，类似 '/css/bootstrap.css':
    var pathname = url.parse(request.url).pathname;
    // 获得对应的本地文件路径，类似 '/srv/www/css/bootstrap.css':
    var filepath = path.join(root, pathname);
    // 获取文件状态:
    fs.stat(filepath, function (err, stats) {
        if (!err && stats.isFile()) {
            // 没有出错并且文件存在:
            console.log('200 ' + request.url);
            // 发送200响应:
            response.writeHead(200);
            // 将文件流导向response:
            fs.createReadStream(filepath).pipe(response);
        } else {
            // 出错了或者文件不存在:
            console.log('404 ' + request.url);
            // 发送404响应:
            response.writeHead(404);
            response.end('404 Not Found');
        }
    });
});

server.listen(80);



console.log('Server is running at http://'+IPAdress);
console.log('分数大屏幕请访问http://'+IPAdress+'/client.html');
console.log('记分员请访问http://'+IPAdress+'/server.html');
open('http://'+IPAdress+'/client.html',"chrome");  // 自动打开默认浏览器
//open('http://'+IPAdress+'/server.html',"chrome");  // 自动打开默认浏览器
open('http://'+IPAdress+'/manager.html',"chrome");  // 自动打开默认浏览器